package org.mokusakura.web.controller;

import com.alibaba.fastjson.JSONObject;
import org.mokusakura.constant.ServletUrlConstant;
import org.mokusakura.constant.SessionAttributeKeyConstant;
import org.mokusakura.domain.Order;
import org.mokusakura.domain.User;
import org.mokusakura.domain.vo.SimpleOrder;
import org.mokusakura.service.PurchaseService;
import org.mokusakura.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

@RestController
public class MakeOrderController {
    public static final String DEFAULT_LOCALE = "en";
    public static final String DEFAULT_STATUS = "1";
    public static final String RESPONSE_KEY_ORDER_ID = "orderId";
    public static final String RESPONSE_KEY_ORDER = "order";
    public static final String ERROR_KEY = "error";
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private UserService userService;

    @PostMapping(value = ServletUrlConstant.MAKE_ORDER_SERVLET_URL)
    public String makeOrder(@RequestBody Order order,
                            @SessionAttribute(value = SessionAttributeKeyConstant.LOGIN_USER) User user) {
        JSONObject jsonObject = new JSONObject();
        order.setUserId(user.getId());
        if (!checkOrder(order)) {
            jsonObject.put("error", "Information Wrong!");
        } else {
            try {
                order = purchaseService.makeOrder(order, user, userService.getUserCart(user));
                if (order != null) {
                    jsonObject.put(RESPONSE_KEY_ORDER_ID, String.valueOf(order.getOrderId()));
                    jsonObject.put(RESPONSE_KEY_ORDER, new SimpleOrder(order));
                }
            } catch (Exception e) {
                jsonObject.put("error", e.getMessage());
            }
        }
        return jsonObject.toJSONString();
    }

    private Boolean checkOrder(Order order) {
        //TODO 检查订单除了locale，status，id，lineItems，orderDate,courier以外的字段
        return true;
    }
}
